﻿using System;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.UI;

public class Soldier : MoveUnit
{
    float timer;
    public Soldier():base()
    {
    }

    void Awake()
    {
        obj = transform.gameObject;
        timer = 0;
    }

    void Start()
    {
        //基本属性
        MaxHP = 100;
        currentHP = MaxHP;
        price = 5;
        reTrBloodThis = this.transform.GetChild(0);
        reTrBloodThis.GetChild(0).GetComponent<Slider>().maxValue = MaxHP;
        reTrBloodThis.gameObject.SetActive(false);
        attackRange = 6;
        attackDamage = 5;
        pos = this.transform.position;

        //技能
        lastAttackTime = Time.time;
        attackInterval = 1.0f;

        // 士兵状态管理初始化
        state = new SoldierStateManager(obj);
        state.InitStateSystem();
        state.Init();

        // 寻路初始化
        m_NavAgent = GetComponent<NavMeshAgent>();

        if ((GameJudge.instance.Player1.transform.position.x < 0 && this.pos.x < 0) || (GameJudge.instance.Player1.transform.position.x > 0 && pos.x > 0))
        {
            this.tag = "Player1_Soldier";
            this.name = "Player1_Soldier";
            this.gameObject.layer = 11;
        }
        else
        {
            this.tag = "Player2_Soldier";
            this.name = "Player2_Soldier";
            this.gameObject.layer = 12;
        }
    }

    void Update()
    {
        // 实时更新目标
        FindTarget();
        //士兵状态转变监听
        state.StateSystem.CurrentState.ProcessTransition();

        NewBlood();
    }

    public override void DoAttack()
    {
        obj.transform.LookAt(target.transform);
        
        if (timer >= attackInterval)
        {
            if (target.tag != "Player 2 castle" && target.tag != "Player 1 castle")
            {
                target.GetComponent<Unit>().BeAttacked(attackDamage);
                if (target.GetComponent<Unit>().currentHP <= 0)
                {
                    target = null;
                }
                timer = 0;
            }
            else
            {
                target.GetComponent<Castle>().BeAttacked(attackDamage);
                timer = 0;
            }
        }
        timer += Time.deltaTime;
    }

    private void NewBlood()
    {
        if(isDisplayBlood)
        {
            reTrBloodThis.gameObject.SetActive(true);
        }
        reTrBloodThis.GetChild(0).GetComponent<Slider>().value = currentHP;
    }
}
